package com.estronger.shopmanage.gaodemap;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.estronger.shopmanage.R;
import com.soonfor.evaluate.base.EvalBaseActivity;

import butterknife.BindView;

/**
 * Created by Administrator on 2018/3/9 0009.
 */

public class LocationActivity extends EvalBaseActivity {

    @BindView(R.id.webView)
    WebView webView;


    private String url = "https://m.amap.com/search/view/keywords=";


    /**
     * 绑定布局文件
     *
     * @return 布局文件ID
     */
    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_statistical_report;
    }

    /**
     * 初始化视图控件
     */
    @Override
    protected void initViews() {
        requestPermission();
        ImageButton iv_back = (ImageButton) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        TextView tv_title = (TextView) findViewById(R.id.title);
        tv_title.setText("楼盘位置");
        WebSettings webSettings = webView.getSettings();
        //webview支持js脚本
        webSettings.setJavaScriptEnabled(true);
        //启用数据库
        webSettings.setDatabaseEnabled(true);
        //设置定位的数据库路径
        String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        webSettings.setGeolocationDatabasePath(dir);
        //启用地理定位
        webSettings.setGeolocationEnabled(true);
        //开启DomStorage缓存
        webSettings.setDomStorageEnabled(true);
        //配置权限
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedIcon(WebView view, Bitmap icon) {
                super.onReceivedIcon(view, icon);
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
                super.onGeolocationPermissionsShowPrompt(origin, callback);

            }
        });

        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.i("test","url ="+url);
                try{
                    if(url.startsWith("androidamap://")){
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                        return true;
                    }else if (url.startsWith("amapuri://search/nearby?")) {
                        return true;
                    }else return false;
                }catch (Exception e){
                    return false;
                }
            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                try{
                    if(url.startsWith("androidamap://")){
                        Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl());
                        startActivity(intent);
                        return true;
                    }else if (url.startsWith("amapuri://search/nearby?")) {
                        return true;
                    }else return false;
                }catch (Exception e){
                    return false;
                }
            }
        });
        //Toast.makeText(this,url + getIntent().getStringExtra("location"),Toast.LENGTH_SHORT).show();
        Log.i("test","url + getIntent().getStringExtra(location)="+url + getIntent().getStringExtra("location"));
        webView.loadUrl(url + getIntent().getStringExtra("location"));

    }

    private void requestPermission() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(getApplicationContext(), "没有权限, 请手动开启定位权限", Toast.LENGTH_SHORT).show();
// 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(LocationActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
        }
    }

    /**
     * 初始化presenter
     */
    @Override
    protected void initPresenter() {

    }

    /**
     * 更新视图控件
     *
     * @param isRefresh
     */
    @Override
    protected void updateViews(boolean isRefresh) {

    }

    public static void start(Context context, String latitude, String longtitude, String location) {
        Intent intent = new Intent(context, LocationActivity.class);
        intent.putExtra("latitude", latitude);
        intent.putExtra("location", location);
        intent.putExtra("longtitude", longtitude);
        context.startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            // 返回上一页面
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
